package itcast.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import itcast.domain.User;
import itcast.service.UserService;
import itcast.service.UserServiceimpl;

/**
 * Servlet implementation class loginServlet
 */
@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public loginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");//解决保存文件乱码问题
		response.setCharacterEncoding("utf-8");//解决保存文件乱码问题
		// TODO Auto-generated method stub
		doGet(request, response);
		//1、获取密码、账号,验证码
		String username=request.getParameter("user");
		String password=request.getParameter("password");
		String verifycode=request.getParameter("verifycode");
		//2、封装对象
		User users=new User();
		users.setUsername(username);
		users.setPassword(password);
		//3、先验证，用户输入验证码
		HttpSession session=request.getSession();
		String checkcode = (String)session.getAttribute("checkcode");
		session.removeAttribute("checkcode");//确保验证码一次性
	    if(checkcode!= null &&checkcode.equalsIgnoreCase(verifycode)) {
			//1、验证码成功开始比对用户名和密码，调用service
			UserService userService=new UserServiceimpl();
			User loginuser =userService.login(users);
			if (loginuser!=null) {
				//登录成功
				//1、登录成功存储信息到session
				session.setAttribute("user", loginuser);
				//2、重定向到欢迎页面！
				response.sendRedirect("index.jsp");
			}else {
				//登录失败
				//设置request值提示信息
				request.setAttribute("lose", "用户名或密码错误");
				request.getRequestDispatcher("login.jsp").forward(request, response);
			}
		}else {
			//验证码错误
			request.setAttribute("lose", "验证码错误！");	
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}
}
